package com.lcc.generate.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * Json工具类
 */
public class JsonUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    static {
        // 为Null时不序列化
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 允许单引号
        MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 允许不带引号的字段名称
        MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 遇到空值处理为空串
        MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){
            @Override
            public void serialize(Object value, JsonGenerator jgen,
                                  SerializerProvider provider) throws IOException, JsonProcessingException {
                jgen.writeString("");
            }
        });
    }

    private JsonUtil() {

    }

    /**
     * JSON字符串转Java对象
     *
     * @param json JSON字符串
     * @param clz  Class<T>
     * @param <T>  <T> 静态方法泛型
     * @return Java对象
     * @throws IOException JSON反序列化异常
     */
    public static <T> T parseObject(String json, Class<T> clz) throws IOException {
        return MAPPER.readValue(json, clz);
    }

}
